"""
面试管理视图
"""
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from django.utils import timezone
from django.db.models import Q, Count, Avg
from django.shortcuts import get_object_or_404
from django.http import StreamingHttpResponse
import json
import requests

from .models import (
    InterviewCategory, InterviewQuestion, InterviewApplication,
    Interview, InterviewResult, InterviewEvaluation, InterviewTask,
    PracticeSession, PracticeMessage, PracticeRecord
)
from .serializers import (
    InterviewCategorySerializer, InterviewQuestionSerializer,
    InterviewApplicationSerializer, InterviewApplicationCreateSerializer,
    InterviewApplicationReviewSerializer, InterviewSerializer,
    InterviewResultSerializer, InterviewResultTeacherSerializer,
    InterviewResultStudentSerializer, InterviewEvaluationSerializer,
    InterviewTaskSerializer, InterviewStatisticsSerializer,
    PracticeSessionSerializer, PracticeSessionCreateSerializer,
    PracticeMessageSerializer, PracticeRecordSerializer, PracticeRecordListSerializer
)
from students.models import Student
from accounts.permissions import IsTeacherOrAdmin, IsStudentUser


class InterviewCategoryViewSet(viewsets.ModelViewSet):
    """面试分类管理"""

    queryset = InterviewCategory.objects.filter(is_active=True)
    serializer_class = InterviewCategorySerializer
    permission_classes = [permissions.IsAuthenticated]


class InterviewQuestionViewSet(viewsets.ModelViewSet):
    """面试题目管理"""

    queryset = InterviewQuestion.objects.filter(is_active=True)
    serializer_class = InterviewQuestionSerializer
    permission_classes = [permissions.IsAuthenticated, IsTeacherOrAdmin]

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)


class InterviewApplicationViewSet(viewsets.ModelViewSet):
    """面试申请管理"""

    queryset = InterviewApplication.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'create':
            return InterviewApplicationCreateSerializer
        elif self.action == 'review':
            return InterviewApplicationReviewSerializer
        return InterviewApplicationSerializer

    def get_queryset(self):
        user = self.request.user
        queryset = InterviewApplication.objects.select_related('student', 'teacher')

        if user.role == 'student':
            # 学生只能看到自己的申请
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(student=student)
        elif user.role in ['teacher', 'admin']:
            # 老师可以看到分配给自己的申请
            if user.role == 'teacher':
                queryset = queryset.filter(teacher=user)

        # 状态筛选
        status_filter = self.request.query_params.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)

        return queryset.order_by('-created_at')

    def perform_create(self, serializer):
        # 学生创建申请时自动设置学生信息
        student = get_object_or_404(Student, user=self.request.user)
        serializer.save(student=student)

    @action(detail=True, methods=['post'], permission_classes=[IsTeacherOrAdmin])
    def review(self, request, pk=None):
        """审核面试申请"""
        application = self.get_object()

        # 只有指定的老师可以审核
        if request.user != application.teacher and request.user.role != 'admin':
            return Response(
                {'error': '只有指定的老师可以审核此申请'},
                status=status.HTTP_403_FORBIDDEN
            )

        serializer = self.get_serializer(application, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save(reviewed_at=timezone.now())

            # 如果审核通过，创建面试记录
            if application.status == 'approved':
                self._create_interview_record(application)

            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def _create_interview_record(self, application):
        """创建面试记录"""
        if application.scheduled_date and application.scheduled_time_start:
            scheduled_datetime = timezone.datetime.combine(
                application.scheduled_date,
                application.scheduled_time_start
            )

            interview = Interview.objects.create(
                application=application,
                student=application.student,
                interviewer=application.teacher,
                interview_type=application.interview_type,
                title=application.title,
                description=application.description,
                scheduled_time=timezone.make_aware(scheduled_datetime),
                location=application.location,
                status='scheduled'
            )

            # 创建面试结果记录
            InterviewResult.objects.create(interview=interview)

            # 更新申请状态
            application.status = 'scheduled'
            application.save()


class InterviewViewSet(viewsets.ModelViewSet):
    """面试记录管理"""

    queryset = Interview.objects.all()
    serializer_class = InterviewSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        queryset = Interview.objects.select_related('student', 'interviewer', 'application')

        if user.role == 'student':
            # 学生只能看到自己的面试
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(student=student)
        elif user.role == 'teacher':
            # 老师可以看到自己负责的面试
            queryset = queryset.filter(interviewer=user)

        # 状态筛选
        status_filter = self.request.query_params.get('status')
        if status_filter:
            queryset = queryset.filter(status=status_filter)

        return queryset.order_by('-scheduled_time')

    @action(detail=False, methods=['get'])
    def schedule(self, request):
        """获取面试安排（日历视图）"""
        user = request.user

        # 获取查询参数
        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')

        # 构建查询集
        queryset = Interview.objects.select_related('student', 'interviewer', 'application')

        # 权限过滤
        if user.role == 'student':
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(student=student)
        elif user.role == 'teacher':
            queryset = queryset.filter(interviewer=user)

        # 日期范围过滤
        if start_date:
            queryset = queryset.filter(scheduled_time__date__gte=start_date)
        if end_date:
            queryset = queryset.filter(scheduled_time__date__lte=end_date)

        # 只返回已安排和进行中的面试
        queryset = queryset.filter(status__in=['scheduled', 'in_progress'])

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'], permission_classes=[IsTeacherOrAdmin])
    def start(self, request, pk=None):
        """开始面试"""
        interview = self.get_object()

        if interview.status != 'scheduled':
            return Response(
                {'error': '只有已安排的面试才能开始'},
                status=status.HTTP_400_BAD_REQUEST
            )

        interview.status = 'in_progress'
        interview.actual_start_time = timezone.now()
        interview.save()

        return Response({'message': '面试已开始'})

    @action(detail=True, methods=['post'], permission_classes=[IsTeacherOrAdmin])
    def complete(self, request, pk=None):
        """完成面试"""
        interview = self.get_object()

        if interview.status != 'in_progress':
            return Response(
                {'error': '只有进行中的面试才能完成'},
                status=status.HTTP_400_BAD_REQUEST
            )

        interview.status = 'completed'
        interview.actual_end_time = timezone.now()
        interview.save()

        # 更新申请状态
        if interview.application:
            interview.application.status = 'completed'
            interview.application.save()

        return Response({'message': '面试已完成'})

    @action(detail=True, methods=['get'])
    def result(self, request, pk=None):
        """获取面试结果"""
        interview = self.get_object()

        try:
            result = interview.interviewresult
            serializer = InterviewResultSerializer(result)
            return Response(serializer.data)
        except InterviewResult.DoesNotExist:
            return Response(
                {'error': '面试结果不存在'},
                status=status.HTTP_404_NOT_FOUND
            )


class InterviewResultViewSet(viewsets.ModelViewSet):
    """面试结果管理"""

    queryset = InterviewResult.objects.all()
    serializer_class = InterviewResultSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        queryset = InterviewResult.objects.select_related('interview__student', 'interview__interviewer')

        if user.role == 'student':
            # 学生只能看到自己的面试结果
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(interview__student=student)
        elif user.role == 'teacher':
            # 老师可以看到自己负责的面试结果
            queryset = queryset.filter(interview__interviewer=user)

        return queryset.order_by('-created_at')

    @action(detail=True, methods=['post'], permission_classes=[IsTeacherOrAdmin])
    def teacher_submit(self, request, pk=None):
        """老师提交面试结果"""
        result = self.get_object()

        # 检查权限
        if request.user != result.interview.interviewer and request.user.role != 'admin':
            return Response(
                {'error': '只有面试官可以提交评价'},
                status=status.HTTP_403_FORBIDDEN
            )

        serializer = InterviewResultTeacherSerializer(result, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def student_submit(self, request, pk=None):
        """学生提交面试反馈"""
        result = self.get_object()

        # 检查权限
        if request.user != result.interview.student.user:
            return Response(
                {'error': '只有参与面试的学生可以提交反馈'},
                status=status.HTTP_403_FORBIDDEN
            )

        serializer = InterviewResultStudentSerializer(result, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class InterviewTaskViewSet(viewsets.ModelViewSet):
    """面试任务管理"""

    queryset = InterviewTask.objects.all()
    serializer_class = InterviewTaskSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        queryset = InterviewTask.objects.select_related('student', 'assigned_by')

        if user.role == 'student':
            # 学生只能看到分配给自己的任务
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(student=student)
        elif user.role == 'teacher':
            # 老师可以看到自己分配的任务
            queryset = queryset.filter(assigned_by=user)

        return queryset.order_by('-created_at')

    def perform_create(self, serializer):
        serializer.save(assigned_by=self.request.user)

    @action(detail=True, methods=['post'])
    def complete(self, request, pk=None):
        """完成任务"""
        task = self.get_object()

        # 检查权限
        if request.user != task.student.user:
            return Response(
                {'error': '只有任务分配的学生可以完成任务'},
                status=status.HTTP_403_FORBIDDEN
            )

        if task.status == 'completed':
            return Response(
                {'error': '任务已经完成'},
                status=status.HTTP_400_BAD_REQUEST
            )

        task.status = 'completed'
        task.completion_date = timezone.now()
        task.save()

        return Response({'message': '任务已完成'})


from rest_framework.decorators import api_view, permission_classes
from datetime import datetime, timedelta


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def interview_statistics(request):
    """面试统计"""
    user = request.user

    # 基础查询集
    if user.role == 'student':
        student = get_object_or_404(Student, user=user)
        applications = InterviewApplication.objects.filter(student=student)
        interviews = Interview.objects.filter(student=student)
    elif user.role == 'teacher':
        applications = InterviewApplication.objects.filter(teacher=user)
        interviews = Interview.objects.filter(interviewer=user)
    else:  # admin
        applications = InterviewApplication.objects.all()
        interviews = Interview.objects.all()

    # 统计数据
    total_applications = applications.count()
    pending_applications = applications.filter(status='pending').count()
    approved_applications = applications.filter(status='approved').count()
    completed_interviews = interviews.filter(status='completed').count()

    # 平均评分
    avg_score = InterviewResult.objects.filter(
        interview__in=interviews,
        teacher_score__isnull=False
    ).aggregate(avg=Avg('teacher_score'))['avg'] or 0

    # 本月面试数量
    this_month = timezone.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    this_month_interviews = interviews.filter(
        scheduled_time__gte=this_month
    ).count()

    data = {
        'total_applications': total_applications,
        'pending_applications': pending_applications,
        'approved_applications': approved_applications,
        'completed_interviews': completed_interviews,
        'average_score': round(float(avg_score), 2),
        'this_month_interviews': this_month_interviews,
    }

    serializer = InterviewStatisticsSerializer(data)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def available_teachers(request):
    """获取可用的面试老师列表"""
    from accounts.models import User

    teachers = User.objects.filter(
        role__in=['teacher', 'admin'],
        is_active=True
    ).values('id', 'first_name', 'last_name', 'username')

    teacher_list = []
    for teacher in teachers:
        full_name = f"{teacher['first_name']} {teacher['last_name']}".strip()
        if not full_name:
            full_name = teacher['username']

        teacher_list.append({
            'id': teacher['id'],
            'name': full_name,
            'username': teacher['username']
        })

    return Response(teacher_list)


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def check_expired_interviews(request):
    """检查并处理过期的面试"""
    from .tasks import InterviewStatusManager

    try:
        manager = InterviewStatusManager()
        results = manager.run_all_checks()

        return Response({
            'message': '面试状态检查完成',
            'results': results
        })
    except Exception as e:
        return Response({
            'error': f'检查失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class PracticeSessionViewSet(viewsets.ModelViewSet):
    """面试练习会话管理"""

    queryset = PracticeSession.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'create':
            return PracticeSessionCreateSerializer
        return PracticeSessionSerializer

    def get_queryset(self):
        user = self.request.user
        queryset = PracticeSession.objects.select_related('student')

        if user.role == 'student':
            # 学生只能看到自己的练习会话
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(student=student)
        elif user.role in ['teacher', 'admin']:
            # 老师和管理员可以看到所有会话
            pass

        return queryset.order_by('-created_at')

    def perform_create(self, serializer):
        # 学生创建练习会话时自动设置学生信息
        student = get_object_or_404(Student, user=self.request.user)
        serializer.save(student=student)

    @action(detail=True, methods=['post'])
    def end(self, request, pk=None):
        """结束练习会话"""
        session = self.get_object()

        if session.status != 'active':
            return Response(
                {'error': '只有进行中的会话才能结束'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 计算持续时间
        if session.started_at:
            duration = timezone.now() - session.started_at
            session.duration_minutes = int(duration.total_seconds() / 60)

        session.status = 'completed'
        session.ended_at = timezone.now()
        session.save()

        # 创建练习记录
        practice_record, created = PracticeRecord.objects.get_or_create(
            session=session,
            defaults={
                'summary': '练习已完成，等待AI生成详细分析报告...',
            }
        )

        return Response({
            'message': '练习会话已结束',
            'record_id': practice_record.id
        })

    @action(detail=True, methods=['post'])
    def messages(self, request, pk=None):
        """发送消息到Dify工作流"""
        session = self.get_object()

        if session.status != 'active':
            return Response(
                {'error': '会话已结束，无法发送消息'},
                status=status.HTTP_400_BAD_REQUEST
            )

        query = request.data.get('query', '')
        if not query:
            return Response(
                {'error': '消息内容不能为空'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 保存用户消息
        user_message = PracticeMessage.objects.create(
            session=session,
            role='user',
            content=query
        )

        # 更新会话消息计数
        session.message_count += 1
        session.save()

        try:
            # 调用Dify工作流
            response_mode = request.data.get('response_mode', 'streaming')

            if response_mode == 'streaming':
                return self._handle_streaming_response(session, request.data)
            else:
                return self._handle_blocking_response(session, request.data)

        except Exception as e:
            return Response(
                {'error': f'调用Dify工作流失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def _handle_streaming_response(self, session, data):
        """处理流式响应"""
        def generate_stream():
            try:
                # 这里应该调用Dify API
                # 暂时返回模拟响应
                assistant_message = PracticeMessage.objects.create(
                    session=session,
                    role='assistant',
                    content='这是一个模拟的AI回复，实际应该调用Dify工作流。'
                )

                # 更新会话消息计数
                session.message_count += 1
                session.save()

                # 返回流式数据格式
                yield f"data: {json.dumps({'event': 'message', 'answer': assistant_message.content, 'conversation_id': session.conversation_id})}\n\n"
                yield f"data: {json.dumps({'event': 'message_end', 'conversation_id': session.conversation_id})}\n\n"

            except Exception as e:
                yield f"data: {json.dumps({'event': 'error', 'message': str(e)})}\n\n"

        response = StreamingHttpResponse(
            generate_stream(),
            content_type='text/event-stream'
        )
        response['Cache-Control'] = 'no-cache'
        response['Connection'] = 'keep-alive'
        return response

    def _handle_blocking_response(self, session, data):
        """处理阻塞式响应"""
        # 创建AI回复消息
        assistant_message = PracticeMessage.objects.create(
            session=session,
            role='assistant',
            content='这是一个模拟的AI回复，实际应该调用Dify工作流。'
        )

        # 更新会话消息计数
        session.message_count += 1
        session.save()

        return Response({
            'event': 'message',
            'answer': assistant_message.content,
            'conversation_id': session.conversation_id,
            'message_id': str(assistant_message.id)
        })


class PracticeRecordViewSet(viewsets.ReadOnlyModelViewSet):
    """面试练习记录管理"""

    queryset = PracticeRecord.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get_serializer_class(self):
        if self.action == 'list':
            return PracticeRecordListSerializer
        return PracticeRecordSerializer

    def get_queryset(self):
        user = self.request.user
        queryset = PracticeRecord.objects.select_related('session', 'session__student')

        if user.role == 'student':
            # 学生只能看到自己的练习记录
            student = get_object_or_404(Student, user=user)
            queryset = queryset.filter(session__student=student)
        elif user.role in ['teacher', 'admin']:
            # 老师和管理员可以看到所有记录
            pass

        return queryset.order_by('-created_at')
